using System.Collections.Generic;
using Framework;
using UnityEngine;

namespace GameCore
{
    public class ObjectSortingManager : MonoSingleton<ObjectSortingManager>
    {
        private Dictionary<string, HashSet<ObjectSorter>> sortables = new();

        public static void AddSortable(ObjectSorter sorter)
        {
            if (!Instance.sortables.ContainsKey(sorter.layerName))
                Instance.sortables.Add(sorter.layerName, new HashSet<ObjectSorter>());
            Instance.sortables[sorter.layerName].Add(sorter);
            sorter.SortingOrder = 2;
            SetTop(sorter);
        }

        public static void RemoveSortable(ObjectSorter sorter)
        {
            if (Instance.sortables.TryGetValue(sorter.layerName, out var sortables))
                sortables.Remove(sorter);
        }

        public static void SetTop(ObjectSorter sorter)
        {
            if (Instance.sortables.TryGetValue(sorter.layerName, out var sortables))
            {
                if (sorter.SortingOrder == 0) return;
                sorter.SortingOrder = 1;
                foreach (var sortable in sortables)
                    sortable.SortingOrder -= 1;
            }
        }
    }
}